<template>
  <div class="inspect-button">
    <!-- 有巡查记录 && 状态不是已结束 -->
    <div
      class="inspect-button-end"
      :style="{
        background: background,
        boxShadow: background === 'transparent' ? 'none' : '0px -3px 10px 0px rgba(0,0,0,0.06)'
      }"
      v-if="gridCode && inspectRecord.length && inspectRecord[inspectRecord.length - 1].inspectionState !== '3'"
    >
      <van-row :gutter="20">
        <van-col :span="12">
          <!-- 巡查中 -->
          <template v-if="inspectRecord[inspectRecord.length - 1].inspectionState === '1'">
            <van-button
              block
              type="info"
              icon="pause-circle-o"
              :disabled="buttonDisabled"
              @click="onChangeStatus(1, '暂停巡查')"
            >
              暂停巡查
            </van-button>
          </template>
          <!-- 暂停中 -->
          <template v-if="inspectRecord[inspectRecord.length - 1].inspectionState === '2'">
            <van-button
              block
              type="info"
              icon="play-circle-o"
              :disabled="buttonDisabled"
              @click="onChangeStatus(2, '继续巡查')"
            >
              继续巡查
            </van-button>
          </template>
        </van-col>
        <van-col :span="12">
          <van-button block type="info" icon="stop-circle-o" :disabled="buttonDisabled" @click="onEnd">
            结束巡查
          </van-button>
        </van-col>
      </van-row>
    </div>
    <!-- 巡查记录小于两条 || （第2条巡查记录不是已结束） -->
    <div
      class="inspect-button-start"
      v-else-if="
        gridCode && (inspectRecord.length < 2 || (inspectRecord[1] && inspectRecord[1].inspectionState !== '3'))
      "
    >
      <van-button block type="info" size="large" icon="play-circle-o" :disabled="buttonDisabled" @click="onStart">
        开始巡查
      </van-button>
    </div>
  </div>
</template>
<script>
import CampusSecurity from '@/api/campussecurity'
import mapPlugin from '@/libs/mapPlugin'
export default {
  props: {
    background: {
      type: String,
      default: 'transparent'
    }
  },
  data() {
    return {
      gridData: [],
      gridCode: '',
      inspectPoint: [],
      inspectRecord: [],
      buttonDisabled: false,
      startPos: [],
      endPos: []
    }
  },
  mounted() {},
  methods: {
    getGrid() {
      return new Promise((resolve, reject) => {
        CampusSecurity.Api.grid({ gridType: this.$route.query.gridType }).then(res => {
          const { status, data } = res.data
          if (status === 0) {
            resolve(data)
          }
        })
      })
    },
    // 判断是否有网格在巡查中，如果有不能再点开始巡查或继续巡查
    async getGridStatus() {
      this.gridData = await this.getGrid()
      const index = this.gridData.findIndex(o => o.inspectionState === '1')
      if (index > -1) {
        this.$toast(`${this.gridData[index].gridName}网格正在巡查`)
      }
      return index > -1
    },
    async onStart() {
      const flag = await this.getGridStatus()
      if (flag) return false
      this.buttonDisabled = true
      mapPlugin.geolocation(result => {
        this.startPos = [result.position.lng, result.position.lat]
        CampusSecurity.Api.start({
          gridCode: this.gridCode,
          longitude: result.position.lng,
          latitude: result.position.lat
        })
          .then(res => {
            const { status, message } = res.data
            if (status === 0) {
              this.$emit('changeStatus')
              this.$toast.success('开始巡查')
            } else {
              this.$toast.fail(message)
            }
            this.buttonDisabled = false
          })
          .catch(() => {
            this.buttonDisabled = false
          })
      })
    },
    async onChangeStatus(type, title) {
      let flag = false
      if (type === 2) {
        flag = await this.getGridStatus()
      }
      if (flag) return false
      this.buttonDisabled = true
      const paramsData = {
        inspectionRecordCode: this.inspectRecord[this.inspectRecord.length - 1].inspectionRecordCode,
        type,
        longitude: type === 3 ? this.endPos[0] : '',
        latitude: type === 3 ? this.endPos[1] : ''
      }
      CampusSecurity.Api.changeStatus(paramsData)
        .then(res => {
          const { status, message } = res.data
          if (status === 0) {
            this.$emit('changeStatus')
            this.$toast.success(title)
          } else {
            this.$toast.fail(message)
          }
          this.buttonDisabled = false
        })
        .catch(() => {
          this.buttonDisabled = false
        })
    },
    onEnd() {
      let isInspect = true
      for (const item of this.inspectPoint) {
        if (!item.inspectionPointRecord.length) {
          isInspect = false
          break
        }
      }
      let message = '是否结束巡查'
      // 有单位未巡查
      if (!isInspect) {
        message = '仍有未巡查点位，是否结束巡查'
      }
      this.$dialog
        .confirm({
          title: '提示',
          message: message,
          confirmButtonText: '是',
          cancelButtonText: '否'
        })
        .then(() => {
          mapPlugin.geolocation(result => {
            this.endPos = [result.position.lng, result.position.lat]
            this.onChangeStatus(3, '结束巡查')
          })
        })
    }
  }
}
</script>
<style scope lang="less">
.inspect-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 2999;
  &-start {
    padding: 32px;
  }
  &-end {
    padding: 24px 32px;
  }
}
</style>
